package com.uzhie.media;

import java.util.Arrays;

/**
 * Created by TangFei on 2018/7/26.
 */
public class MediaByteUtil {

    public static int parseByteArrayToInt(byte[] bytes, int pos, int length) throws RuntimeException {
        if (pos + length > bytes.length) {
            throw new ArrayIndexOutOfBoundsException("数组下标越界");
        }
        length = length > 4 ? 4 : length;
        byte[] temp = new byte[length];
        System.arraycopy(bytes, pos, temp, 0, length);
        int result = 0;
        for (int i = 0; i < length; i++) {
            result += (temp[i] & 0xFF) << ((length - 1 - i) * 8);
        }
        return result;
    }


    public static byte[] integerTo2Bytes(int value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >>> 8) & 0xFF);
        result[1] = (byte) (value & 0xFF);
        return result;
    }



    public static byte[] concatAll(byte[] first, byte[]... rest) {
        int totalLength = first.length;
        for (byte[] array : rest) {
            if (array != null) {
                totalLength += array.length;
            }
        }
        byte[] result = Arrays.copyOf(first, totalLength);
        int offset = first.length;
        for (byte[] array : rest) {
            if (array != null) {
                System.arraycopy(array, 0, result, offset, array.length);
                offset += array.length;
            }
        }
        return result;
    }

}
